<?php
namespace app\admin\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Request;
use think\captcha\facade\Captcha;
use think\facade\Db;

class Tool extends BaseController
{
    protected $data = [];
    protected $code = 1;
    protected $msg = 'ok';
    // 初始化
    protected function initialize()
    {
        $this->data = Request::param();
        \think\facade\Config::load('extra/config', 'extra');
        $auth = \app\admin\auth\Auth::check();
        if(!$auth)
        {
        //    echo 'error';
        //    $error = \app\admin\auth\Auth::error()[0];
        //    $this->fail($error);
        }
    }
    public function test()
    {
        $res = $this->renderClass("app\\admin\\model",'Article','model');
        echo '<textarea>';
        echo $res;
        echo '</textarea>';
        die;
    }
    /**
     * [getTables 获取tables]
     * @return [type] [description]
     */
    public function getTables($db='tptest')
    {

        return Db::query('select table_name,TABLE_COMMENT from information_schema.tables where TABLE_SCHEMA=:db',['db'=>$db]);
    }
    /**
     * [strtoupper 字符串转换为首字母大写eg:'admin_test'>'AdminTest']
     * 可用于构造类名
     * @return [type] [description]
     */
    public function strtoupper($str)
    {
        $str = str_replace('_', ' ', $str);
        $str = ucwords($str);
        return str_replace(' ','',$str);
    }
    public function buildMenuByTableInfo($table)
    {
        $menu['link'] = '/'.$this->strtoupper($table['table_name']);
        $menu['name'] =  $table['TABLE_COMMENT'];
        return $menu;
    }
    /**
     * [buildClassFile 创建类文件]
     * @param  [type] $name_space [命名空间]
     * @param  [type] $class_name [类名]
     * @param  [type] $class_body [具体代码]
     * @return [type]             [description]
     */
    public function buildClassFile($filename,$class_body)
    {
        $baseDir = '../';
        $file = array_slice(explode('\\', $filename) , -1)[0];
        echo $file;
        $dir = implode('/',array_slice(explode('\\', $filename) , 0,-1));
        
        if(!is_dir($baseDir.$dir)){
            $res=mkdir(iconv("UTF-8", "GBK", $baseDir.$dir),0777,true); 
            if ($res){
                echo "目录 $dir 创建成功";
            }else{
                echo "目录 $dir 创建失败";
            }
        }
        file_put_contents($baseDir.$dir.'/'.$file, $class_body);
    }
    public function outinfo()
    {
        $res = $this->getTables('tptest');
        //var_dump($res);
        // foreach ($res as $key => $value) {
        //     $data[] = $this->buildMenuByTableInfo($value);
        // }
        // var_dump($data);
        
        //批量生成类文件
        foreach ($res as $key => $value) {
            $data[] = $this->strtoupper($value['table_name']);
        }
        $this->buildClassList('app\api\controller',$data,'controller');//创建控制器
        $this->buildClassList('app\api\model',$data,'model');//创建模型
        die;
    }
    public function buildClassList($namespace,$class_list,$class_type='')
    {
        if($class_type==''){
            $tmp = 'test';
        }else{
            $tmp = $this->getClasstmp($class_type);
        }
        foreach ($class_list as $key => $value) {
           $class_body = $this->renderClass($namespace, $value, $tmp);
           $this->buildClassFile($namespace."\\".$value.".php",$class_body);
        }
    }
    public function renderClass($namespace,$className, $tmp)
    {
        $vars = [
            'className'=>$className,
            'namespace'=>$namespace,
            'actionSuffix'=>''
        ];

        foreach($vars as $k=>$v)
        {
            $tmp = str_replace("{%$k%}", $v, $tmp);
        }
        return $tmp;
    }
    public function getClasstmp($class_type)
    {
        $access_class_type = [
            'controller',
            'model'
        ];
        if(!in_array($class_type, $access_class_type)){
            return 'no class type.';
        }
        $tmp_root = 'classtemp';
        $tmp_path = '../'.$tmp_root.'/'.$class_type.'.stub';
        $tmp = file_get_contents($tmp_path);
        return $tmp;
    }
    /**
     * [getFields 获取表的所有字段名]
     * @param  [type] $table [description]
     * @param  [type] $db    [description]
     * @return [type]        [description]
     */
    function getFields($table,$db)
    {
        return Db::query('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME =:table and TABLE_SCHEMA=:db',['table'=>$table,'db'=>$db]);
    }
    /**
     * [buildView view视图生成器]
     * @return [type] [description]
     */
    function buildView()
    {
        $view['elements'] = [
            '<div>con1</div>',
            '<div>con2</div>'
        ];
        $view['jslist'] = [
            '/usejs/js.js',
            '/usejs/js1.js'
        ];
        $view['script'] = [
            '<script _name="a"></script>',
            '<script _name="b"></script>'
        ];
    }
    function buildElement()
    {
        $element['html'] = '<div></div>';
        $element['jslist'] = [
            '/html/js.js'
        ];
        $element['script'] =  '<script></script>';
    }
    function pregGet()
    {
        $tmp = 'fs
        <element>
        <div> </div>f
        </element>fs
        <jsfilelist>
            <script src="aa/js.js"></script>
            <script src="aa/js.js"></script>
        </jsfilelist>
        <jsscript>
        <script>var a=12;</script>
        </jsscript>
        ';
        $pattern = '/<element>([\W\w\S\s]*)<\/element>/i';
        preg_match_all($pattern, $tmp,$elements,PREG_OFFSET_CAPTURE);
        $pattern = '/<jsfilelist>([\S\s]*)<\/jsfilelist>/';
        preg_match_all($pattern, $tmp,$jslist,PREG_OFFSET_CAPTURE);
        $pattern = '/<jsscript>([\S\s]*)<\/jsscript>/';
        preg_match_all($pattern, $tmp,$jsscript,PREG_OFFSET_CAPTURE);
        echo '<textarea style="width:100%;height:300px">';
        var_dump($elements);
        var_dump($jslist);
        var_dump($jsscript);
        echo '</textarea>';
        die;

    }
    /**
     * [preglayuiuse 提取layuiuse中的引用的模块]
     * @return [type] [description]
     */
    function preglayuiuse()
    {
        $tmp ='
            <script>
            var c=12;
            layui.use(["table","form","jquery"],function () {
                let table = layui.table;
                let form = layui.form;
                let $ = layui.jquery;
        
                let MODULE_PATH = "role/";
            })
            </script>
            ';
        $pattern = '/layui.use\(\[([\W\w]*)\]/';
        preg_match_all($pattern, $tmp,$uselist,PREG_OFFSET_CAPTURE);
        echo '<textarea style="width:100%;height:300px">';
        $uselist = explode(',',preg_replace("/[\'\"]/", '',$uselist[1][0][0]));
        var_dump($uselist);
        //根据引用列表生成新的包裹代码
        $new_pack_script = "layui.use([\"".implode('","',$uselist)."\"],function(){";
        echo $new_pack_script;
        //移除layui.use包裹外层的代码
        $tmps = explode("\n",$tmp);
        //var_dump($tmps);
        $layui_use_exist = false;
        $layui_last_kh = 0;
        foreach ($tmps as $key => $value) {
            $pos = strpos($value,'layui.use');
            if($pos!==false){
                $tmps[$key] = '';
                $layui_use_exist = true;
            }
            //记录查找最后一组 '})' 的位置
            
            $pos = strpos($value,'}');
            if($pos!==false){
                $layui_last_kh = $key;
            }

            //移除引用生成的"layui.table"这种类型的代码行
            $pos = strpos($value,'layui.');
            if($pos!==false){
                $tmps[$key] = '';
            }
        }
        if($layui_use_exist){
            //移除layui.use(,function(){ 对应末尾的括号"})"
            $tmps[$layui_last_kh] = '';
        }
        //重新合并生成去掉了layui.use的代码
        $newscript = implode("\n",$tmps);
        echo $newscript;
        echo '</textarea>';
        die;
    }
}
